import { defineStore } from 'pinia'
import { store } from '../index'
import { getConfig, verifyLicense } from '@/api/basic'
import qs from 'qs'
import { useAppStoreWithOut } from '@/store/modules/app'
import { ElMessage, ElMessageBox } from 'element-plus'

const appStore = useAppStoreWithOut()
export interface BasicState {
  title: string
  footer: any
  header: any
  main: any
  icon: any
  login: any
  isLoginVerify: boolean
  isLoginCaptcha: boolean
  navigation: Array<any>
  layout: 'horizontal'
  isLoadedConfig: boolean
  isActivationLicense: boolean
  useFirstQuery: any
  firstQuery: any
  ui: any
  isLoading: boolean
  loadingTimer: any
  project: any
  regist: any
  kfConfig: any
}

export const useBasicStore = defineStore('basic', {
  state: (): BasicState => ({
    title: '',
    footer: null,
    header: { image: '', text: '' },
    main: { background: '' },
    icon: { file: {} },
    login: { title: '', background: '' },
    isLoginVerify: true, // 是否需要登录（默认true需要）
    isLoginCaptcha: false, // 登录是否开启验证码
    navigation: [],
    layout: 'horizontal',
    isLoadedConfig: false,
    isActivationLicense: false, // 是否需要校验license
    useFirstQuery: false, // 是否保存页面首次加载的query参数，配置成字符串数组，只取给定的key
    firstQuery: {}, // 页面首次加载的query参数
    ui: null,
    isLoading: false, // 通用页面加载中
    loadingTimer: null,
    project: null,
    regist: [], // 注册页面配置
    kfConfig: null // 客服链接配置
  }),
  getters: {
    getTitle(): string {
      return this.title
    },
    getFooter(): any {
      return this.footer
    },
    getHeader(): any {
      return this.header
    },
    getMain(): any {
      return this.main
    },
    getIcon(): any {
      return this.icon
    },
    getLogin(): any {
      return this.login
    },
    getNavigation(): Array<any> {
      return this.navigation
    },
    getLayout(): string {
      return this.layout
    },
    getIsLoadedConfig(): boolean {
      return this.isLoadedConfig
    },
    getIsLoginVerify(): boolean {
      return this.isLoginVerify
    },
    getIsLoginCaptcha(): boolean {
      return this.isLoginCaptcha
    },
    getIsActivationLicense(): boolean {
      return this.isActivationLicense
    },
    getIsLoading(): boolean {
      return this.isLoading
    },
    getUI(): any {
      return this.ui
    },
    getUseFirstQuery(): any {
      return this.useFirstQuery
    },
    getFirstQuery(): any {
      return this.firstQuery
    },
    getProject(): any {
      return this.project
    },
    getRegist(): any {
      return this.regist
    }
  },
  actions: {
    async fetchConfigs(): Promise<void> {
      const res = await getConfig()
      if (res && res.configs) {
        this.title = res.configs.title
        appStore.setTitle(this.title)
        this.main = res.configs.main
        this.initFavicon(this.main?.favicon || this.main?.icon)
        this.footer = res.configs.footer
        this.header = res.configs.header
        this.icon = res.configs.icon
        this.login = res.configs.login
        this.navigation = res.configs.navigation
        this.layout = res.configs.layout
        this.ui = res.configs.ui
        this.isLoadedConfig = true
        this.isLoginVerify =
          res.configs.login && res.configs.login.hasOwnProperty('verify')
            ? res.configs.login.verify
            : true
        this.isLoginCaptcha = !!res.configs?.login?.captcha
        this.isActivationLicense = res.configs.login && res.configs.login.activation
        this.project = res.configs.project
        this.regist = res.configs.regist || {}
        this.useFirstQuery = res.configs.useFirstQuery || false
        this.kfConfig = res.configs.kf
        if (this.kfConfig?.url) {
          this.initKF(this.kfConfig?.url)
        }
      }
      return Promise.resolve(res?.configs)
    },
    cacheFirstQuery() {
      return new Promise((resolve) => {
        const queryStr = (location.href.split('?')[1] || '').replace(/#\/\S*$/, '')
        const params = qs.parse(queryStr)
        this.firstQuery = Array.isArray(this.useFirstQuery)
          ? this.useFirstQuery.reduce((t, c) => {
              if (params[c]) {
                t[c] = params[c]
              }
              return t
            }, {})
          : params
        resolve(this.firstQuery)
      })
    },
    // 如果配置了校验license
    async checkLicense(retry = false): Promise<any> {
      return new Promise(async (resolve, reject) => {
        let res: any
        if (!retry) {
          res = await verifyLicense({ license_code: '' })
        }
        if (!retry && res.error_code === 200) {
          this.isActivationLicense = false
          resolve(true)
        } else {
          ElMessageBox.prompt('请输入激活码', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /\S+/,
            inputErrorMessage: '请输入激活码'
          })
            .then(async ({ value }) => {
              const res: any = await verifyLicense({ license_code: value })
              if (res.error_code === 200) {
                this.isActivationLicense = false
                ElMessage({
                  type: 'success',
                  message: res.error_msg || `激活码校验成功`
                })
                setTimeout(() => {
                  window.location.reload()
                }, 1000)
                resolve(true)
              } else {
                ElMessage({
                  type: 'warning',
                  message: res.error_msg || `激活码校验失败`
                })
                this.checkLicense(true)
                reject()
              }
            })
            .catch(() => {
              this.checkLicense(true)
              reject()
            })
        }
      })
    },
    toggleLoading(is?: boolean): void {
      if (is === undefined) {
        this.isLoading = !this.isLoading
      } else {
        this.isLoading = is
      }
      if (this.loadingTimer) {
        clearTimeout(this.loadingTimer)
      }
      if (this.isLoading) {
        this.loadingTimer = setTimeout(() => {
          this.isLoading = true
        }, 60000)
      }
    },
    initKF(src: any): void {
      setTimeout(() => {
        const _53code = document.createElement('script')
        _53code.async = true
        _53code.src = src
        const s: any = document.getElementsByTagName('script')[0]
        s.parentNode.insertBefore(_53code, s)
      }, 1000)
    },
    initFavicon(icoUrl: any) {
      const link: any =
        document.querySelector("link[rel*='icon']") || document.createElement('link')
      link.type = 'image/x-icon'
      link.rel = 'shortcut icon'
      link.href = icoUrl || '/favicon.ico'
      document.getElementsByTagName('head')[0].appendChild(link)
    }
  }
})

export const useBasicStoreWithOut = () => {
  return useBasicStore(store)
}
